import pandas as pd
import numpy as np
import random
from datetime import datetime, timedelta
from lightweight_charts import Chart


def generate_sample_data():
    start_date = datetime(2020, 1, 1)
    end_date = datetime(2025, 1, 1)
    num_days = (end_date - start_date).days
    dates = [start_date + timedelta(days=i) for i in range(num_days)]
    prices = np.cumprod(1 + np.random.normal(0, 0.01, num_days))
    drawdown = np.random.uniform(0, 0.2, num_days)
    orders = []
    for _ in range(20):
        order_date = random.choice(dates)
        order_type = random.choice(['Buy', 'Sell'])
        price = random.uniform(prices.min(), prices.max())
        orders.append({'Date': order_date, 'Type': order_type, 'Price': price})
    annual_returns = {year: random.uniform(-0.2, 0.3) for year in range(2020, 2025)}
    return dates, prices, drawdown, orders, annual_returns


def main():
    dates, prices, drawdown, orders, annual_returns = generate_sample_data()
    df = pd.DataFrame({'Date': dates, 'Price': prices, 'Drawdown': drawdown})
    df['Date'] = pd.to_datetime(df['Date'])

    chart = Chart()

    # # 添加时间序列线图
    # line_plot = chart.add_line_series()
    # line_plot.set(df['Date'], df['Price'])

    # 添加回撤曲线子图
    drawdown_chart = chart.create_subchart()
    #drawdown_plot = drawdown_chart.add_line_series(color='red')
    #drawdown_plot.set(df['Date'], df['Drawdown'])

    # 展示回测结果指标
    metrics = {
        'Sharpe Ratio': np.random.uniform(0, 2),
        'Sortino Ratio': np.random.uniform(0, 3),
        'Max Drawdown': df['Drawdown'].max()
    }
    for metric, value in metrics.items():
        chart.marker(
            time=df['Date'].iloc[0],
            position='aboveBar',
            color='blue',
            shape='arrowUp',
            text=f'{metric}: {value:.2f}'
        )

    # 展示订单详情
    for order in orders:
        time_index = df[df['Date'] == order['Date']].index[0]
        chart.marker(
            time=df['Date'].iloc[time_index],
            position='belowBar',
            color='green' if order['Type'] == 'Buy' else 'red',
            shape='arrowDown',
            text=f"{order['Type']} at {order['Price']:.2f}"
        )

    # 添加多年收益柱状图子图
    annual_chart = chart.create_subchart()
    years = list(annual_returns.keys())
    returns = list(annual_returns.values())
    # bar_plot = annual_chart.add_bar_series()
    # bar_plot.set([{'time': year, 'open': 0, 'high': r if r > 0 else 0,
    #                'low': r if r < 0 else 0, 'close': r} for year, r in zip(years, returns)])

    chart.show()


if __name__ == "__main__":
    main()
